package com.glory.brepda.activity.check;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.activity.ScanTestEditTextActivity;
import com.glory.brepda.adapter.QCDetailCheckAdapter;
import com.glory.brepda.adapter.QCDetailMeasurementAdapter;
import com.glory.brepda.adapter.QCDetailSPCAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.MaintenanceProgressBean;
import com.glory.brepda.entity.QCCheckBean;
import com.glory.brepda.entity.QCSubmitBean;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.entity.stateChangeEntity;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import androidx.appcompat.app.AlertDialog;

import butterknife.BindView;

public class QCDetailActivity extends BaseActivity {


    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.rvCheckList)
    RecyclerView rvCheckList;
    @BindView(R.id.rvMeasurementList)
    RecyclerView rvMeasurementList;
    @BindView(R.id.rvSPCList)
    RecyclerView rvSPCList;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.etCheckQty)
    FreeUI_ClearEditText etCheckQty;
    @BindView(R.id.etDefectQty)
    FreeUI_ClearEditText etDefectQty;

    @BindView(R.id.tvTempSaveFrom)
    TextView tvTempSaveFrom;

    private QCDetailCheckAdapter mCheckAdapter;
    private QCDetailMeasurementAdapter mMeasurementAdapter;
    private QCDetailSPCAdapter mSPCAdapter;
    private QCCheckBean.QCFORMDTO qcForm;
    private int currentUploadPosition = -1;
    private String mFilePath = "";
    private LoadingPopupView loadingPopup;

    private String fromVerifyFlag;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_qcdetail;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {

        setMainLayout(llMain);
        tvTitle.setText("QC详情");
        tvBaseSubmit.setText("提交");
        initRecyclerView(rvCheckList, this);
        mCheckAdapter = new QCDetailCheckAdapter(null, new QCDetailCheckAdapter.OnUploadClickListener() {
            @Override
            public void onUploadClick(int position) {
                currentUploadPosition = position;
                mFilePath = Environment.getExternalStorageDirectory().getPath() + "/mytest.png";
                Uri mUri = Uri.fromFile(new File(mFilePath));
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                startActivityForResult(openCameraIntent, 1);

//                Matisse.from(QCDetailActivity.this)
//                        .choose(MimeType.of(MimeType.JPEG, MimeType.PNG))
//                        .countable(true)
//                        .maxSelectable(99)
//                        .imageEngine(new GlideEngine())
//                        .forResult(1);

            }
        });
        mCheckAdapter.isFirstOnly(true);
        mCheckAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rvCheckList.setAdapter(mCheckAdapter);
        initRecyclerView(rvMeasurementList, this);
        mMeasurementAdapter = new QCDetailMeasurementAdapter(null, new QCDetailMeasurementAdapter.OnUploadClickListener() {
            @Override
            public void onUploadClick(int position) {
                currentUploadPosition = position;
                mFilePath = Environment.getExternalStorageDirectory().getPath() + "/mytest.png";
                Uri mUri = Uri.fromFile(new File(mFilePath));
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                startActivityForResult(openCameraIntent, 2);

//                Matisse.from(QCDetailActivity.this)
//                        .choose(MimeType.of(MimeType.JPEG, MimeType.PNG))
//                        .countable(true)
//                        .maxSelectable(99)
//                        .imageEngine(new GlideEngine())
//                        .forResult(2);
            }
        });
        mMeasurementAdapter.isFirstOnly(true);
        mMeasurementAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rvMeasurementList.setAdapter(mMeasurementAdapter);
        initRecyclerView(rvSPCList, this);
        mSPCAdapter = new QCDetailSPCAdapter(null, new QCDetailSPCAdapter.OnUploadClickListener() {
            @Override
            public void onUploadClick(int position) {
                currentUploadPosition = position;
                mFilePath = Environment.getExternalStorageDirectory().getPath() + "/mytest.png";
                Uri mUri = Uri.fromFile(new File(mFilePath));
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                startActivityForResult(openCameraIntent, 3);

//                Matisse.from(QCDetailActivity.this)
//                        .choose(MimeType.of(MimeType.JPEG, MimeType.PNG))
//                        .countable(true) // 是否显示选择顺序
//                        .maxSelectable(99)
//                        .imageEngine(new GlideEngine()) // 自定义图片加载方式
//                        .forResult(3);
            }
        });
        mSPCAdapter.isFirstOnly(true);
        mSPCAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rvSPCList.setAdapter(mSPCAdapter);

        qcForm = (QCCheckBean.QCFORMDTO) getIntent().getSerializableExtra("qc_form");
        assert qcForm != null;
        mCheckAdapter.setNewData(qcForm.getITEMLINES());
        mCheckAdapter.notifyDataSetChanged();
        mMeasurementAdapter.setNewData(qcForm.getDATALINES());
        mMeasurementAdapter.notifyDataSetChanged();
        mSPCAdapter.setNewData(qcForm.getSPCLINES());
        mSPCAdapter.notifyDataSetChanged();
        fromVerifyFlag = qcForm.getFROM_VERIFY_FLAG();

        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        // 设置检验数初始值
        if (qcForm.getCHECK_QTY() != null) {
            etCheckQty.setText(String.valueOf(qcForm.getCHECK_QTY()));
        } else {
            etCheckQty.setText("5");
        }
        
        // 设置缺陷数初始值
        if (qcForm.getDEFECT_QTY() != null) {
            etDefectQty.setText(String.valueOf(qcForm.getDEFECT_QTY()));
        } else {
            etDefectQty.setText("0");
        }

    }

    @Override
    protected void initData() {

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbCheck:
                        rvCheckList.setVisibility(View.VISIBLE);
                        rvMeasurementList.setVisibility(View.GONE);
                        rvSPCList.setVisibility(View.GONE);
                        break;
                    case R.id.rbMeasurement:
                        rvCheckList.setVisibility(View.GONE);
                        rvMeasurementList.setVisibility(View.VISIBLE);
                        rvSPCList.setVisibility(View.GONE);
                        break;
                    case R.id.rbSPC:
                        rvCheckList.setVisibility(View.GONE);
                        rvMeasurementList.setVisibility(View.GONE);
                        rvSPCList.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });

        tvBaseSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if("Y".equals(fromVerifyFlag)){
                    firstSubmit();//第一次提交为临时保存，第二次提交才是正式提交
                }else{
                    secondSubmit();//二次提交，和原有逻辑保持一致
                }

            }
        });

        tvTempSaveFrom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTvTempSaveFrom("N", null, false);
            }
        });

    }

    public void secondSubmit(){
            String type = "N";

            for (QCCheckBean.QCFORMDTO.ITEMLINESDTO item : mCheckAdapter.getData()) {
                if ("NG".equalsIgnoreCase(item.getRESULT_FLAG())) {
                    type = "Y";
                }
            }
            for (QCCheckBean.QCFORMDTO.DATALINESDTO item : mMeasurementAdapter.getData()) {
                if ("NG".equalsIgnoreCase(item.getRESULT_FLAG())) {
                    type = "Y";
                }
            }
            for (QCCheckBean.QCFORMDTO.SPCLINESDTO item : mSPCAdapter.getData()) {
                if ("NG".equalsIgnoreCase(item.getRESULT_FLAG())) {
                    type = "Y";
                }
            }

            if (type.equals("Y")) {
                FreeApi_DialogUtils.getConfirmAndCancelDialog(QCDetailActivity.this, "存在NG的项目提交提示是否临时保存?", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        submit("Y", null, false);
                    }
                }, () -> {
                    submit("N", null, false);
                }).show(getSupportFragmentManager(), "SUBMIT_DIALOG");
            } else {
                submit("N", null, false);
            }
    }
    private void submit(String ACTIONTYPE, QCSubmitBean.QCFORMDTO qcBean, boolean subType) {


        loadingPopup = (LoadingPopupView) new XPopup.Builder(this)
//                .dismissOnBackPressed(false)    // 禁止返回键关闭
                .dismissOnTouchOutside(false)   // 禁止点击外部关闭
                .asLoading("正在提交，请稍候...")
                .show();

        FreeUI_EntityCallBack<BaseResponseBean<QCSubmitBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<QCSubmitBean>>
                (new TypeToken<BaseResponseBean<QCSubmitBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<QCSubmitBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    loadingPopup.dismiss();
                    if (response.body().getResponse().getBody() != null && response.body().getResponse().getBody().getRESULTMESSAGE().equals("需要传递复核人以及复核原因")) {
                        showInputDialog("需要传递复核人以及复核原因", response.body().getResponse().getBody().getQCFORM(), ACTIONTYPE);
                    } else {
                        showToast("提交成功", true);
                        setResult(Activity.RESULT_OK);
                        finish();
                    }
                } else {
                    loadingPopup.dismiss();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<QCSubmitBean>> response) {
                super.onError(response);
                loadingPopup.dismiss();
                loadError(response.getException(), "CPCQCFORMCOMPLETE");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", ACTIONTYPE);
        if (subType) {
            map.add("QCFORM", new JsonParser().parse(new Gson().toJson(qcBean)).getAsJsonObject());
        } else {
            if (!etCheckQty.getText().toString().isEmpty()){
                qcForm.setCHECK_QTY(Double.valueOf(etCheckQty.getText().toString()));
            }
            if (!etDefectQty.getText().toString().isEmpty()){
                qcForm.setDEFECT_QTY(Double.valueOf(etDefectQty.getText().toString()));
            }
            // 为解决qc任务校验提交后加载时间过长问题，图片上传改成第一次提交的时候保存，第二次提交只提交数据不提交图片
            for (QCCheckBean.QCFORMDTO.ITEMLINESDTO item : qcForm.getITEMLINES()) {
                item.setANNEX_URL(""); // 清空ANNEX_URL字段
                item.getANNEX_URL_LIST().clear();
            }
            for (QCCheckBean.QCFORMDTO.DATALINESDTO item : qcForm.getDATALINES()) {
                item.setANNEX_URL(""); // 清空ANNEX_URL字段
                item.getANNEX_URL_LIST().clear();
            }
            for (QCCheckBean.QCFORMDTO.SPCLINESDTO item : qcForm.getSPCLINES()) {
                item.setANNEX_URL(""); // 清空ANNEX_URL字段
                item.getANNEX_URL_LIST().clear();
            }
            qcForm.setITEMLINES(mCheckAdapter.getData());
            qcForm.setDATALINES(mMeasurementAdapter.getData());
            qcForm.setSPCLINES(mSPCAdapter.getData());
            map.add("QCFORM", new JsonParser().parse(new Gson().toJson(qcForm)).getAsJsonObject());
        }
        NetUtils.requestPostNet("IF.CPCQCFORMCOMPLETE", "Common", QCDetailActivity.this, map, callBack);


    }

    public void setTvTempSaveFrom(String ACTIONTYPE, QCSubmitBean.QCFORMDTO qcBean, boolean subType){
        loadingPopup = (LoadingPopupView) new XPopup.Builder(this)
//                .dismissOnBackPressed(false)    // 禁止返回键关闭
                .dismissOnTouchOutside(false)   // 禁止点击外部关闭
                .asLoading("正在提交，请稍候...")
                .show();

        FreeUI_EntityCallBack<BaseResponseBean<QCSubmitBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<QCSubmitBean>>
                (new TypeToken<BaseResponseBean<QCSubmitBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<QCSubmitBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    loadingPopup.dismiss();
                    showToast("提交成功", true);
                    setResult(Activity.RESULT_OK);
                    finish();
                } else {
                    loadingPopup.dismiss();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<QCSubmitBean>> response) {
                super.onError(response);
                loadingPopup.dismiss();
                loadError(response.getException(), "CPCQCFORMCOMPLETE");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "TEMPSAVEFORM");
        if (subType) {
            map.add("QCFORM", new JsonParser().parse(new Gson().toJson(qcBean)).getAsJsonObject());
        } else {
            if (!etCheckQty.getText().toString().isEmpty()){
                qcForm.setCHECK_QTY(Double.valueOf(etCheckQty.getText().toString()));
            }
            if (!etDefectQty.getText().toString().isEmpty()){
                qcForm.setDEFECT_QTY(Double.valueOf(etDefectQty.getText().toString()));
            }
            qcForm.setITEMLINES(mCheckAdapter.getData());
            qcForm.setDATALINES(mMeasurementAdapter.getData());
            qcForm.setSPCLINES(mSPCAdapter.getData());
            map.add("QCFORM", new JsonParser().parse(new Gson().toJson(qcForm)).getAsJsonObject());
        }
        NetUtils.requestPostNet("IF.CPCQCFORMWORKING", "QCIMGUPLOAD", QCDetailActivity.this, map, callBack);

    }
    public void checkDate(long objectRrn){
        FreeUI_EntityCallBack<BaseResponseBean<MaintenanceProgressBean>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaintenanceProgressBean>>
                (new TypeToken<BaseResponseBean<MaintenanceProgressBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaintenanceProgressBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    String resultMessage="";
                    List<MaintenanceProgressBean.MaintenanceProgressList> progressList = response.body().getResponse().getBody().getSlelectItemProgressList();
                    for(MaintenanceProgressBean.MaintenanceProgressList tempList:progressList){
                        if(StringUtils.isBlank(tempList.getRESULT())){//校验项目校验结果不是成功
                            resultMessage = resultMessage+tempList.getITEM_NAME()+"(所属用户组:"+tempList.getUSER_GROUP()+")、";
                        }
                    }

                  if(StringUtils.isNotBlank(resultMessage)){
                      showCustomDialog(resultMessage.substring(0,resultMessage.length()-1));
                   }else{
                      secondSubmit();//提交
                  }

                }

            }

            @Override
            public void onError(Response<BaseResponseBean<MaintenanceProgressBean>> response) {
                super.onError(response);
                loadError(response.getException(),"checkDate");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("OBJECTRRN", objectRrn);
        map.addProperty("ACTIONTYPE", "VERFYFORM");
        NetUtils.requestPostNet("IF.CPCQCFORMWORKING", "Common", QCDetailActivity.this, map, callBack);
    }

    public void firstSubmit(){

        FreeUI_EntityCallBack<BaseResponseBean<QCSubmitBean>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<QCSubmitBean>>
                (new TypeToken<BaseResponseBean<QCSubmitBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<QCSubmitBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    checkDate(qcForm.getOBJECTRRN());//校验是否存在还没有校验结果的校验项
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<QCSubmitBean>> response) {
                super.onError(response);
                loadingPopup.dismiss();
                loadError(response.getException(), "firstSubmit");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "TEMPSAVEFORM");
        if (!etCheckQty.getText().toString().isEmpty()){
            qcForm.setCHECK_QTY(Double.valueOf(etCheckQty.getText().toString()));
        }
        if (!etDefectQty.getText().toString().isEmpty()){
            qcForm.setDEFECT_QTY(Double.valueOf(etDefectQty.getText().toString()));
        }
        qcForm.setITEMLINES(mCheckAdapter.getData());
        qcForm.setDATALINES(mMeasurementAdapter.getData());
        qcForm.setSPCLINES(mSPCAdapter.getData());
        map.add("QCFORM", new JsonParser().parse(new Gson().toJson(qcForm)).getAsJsonObject());
        NetUtils.requestPostNet("IF.CPCQCFORMWORKING", "QCIMGUPLOAD", QCDetailActivity.this, map, callBack);

    }

    private void showCustomDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("以下校验项校验结果为空:"+message);
        builder.setPositiveButton("确定", null);

        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private JsonArray toJsonArray(Object obj) {
        List<Object> list = new ArrayList<>();
        list.add(obj);
        return new Gson().toJsonTree(list).getAsJsonArray();
    }


    private void showInputDialog(String message, QCSubmitBean.QCFORMDTO qcBean, String ACTIONTYPE) {
        FreeUI_GeneralFragmentDialog freeU_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_qc_input, null);
        TextView title = view.findViewById(R.id.title);
        title.setText(message);
        FreeUI_ClearEditText reason = view.findViewById(R.id.RECHECK_REASON);
        FreeUI_ClearEditText person = view.findViewById(R.id.RECHECK_PERSON);
        TextView tvConfirm = view.findViewById(R.id.tvConfirm);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        tvCancel.setOnClickListener(v -> {
            freeU_generalFragmentDialog.dismiss();
        });
        tvConfirm.setOnClickListener(v -> {
            if (reason.getText().toString().isEmpty()) {
                showToast("请输入复核原因", false);
                return;
            }
            if (person.getText().toString().isEmpty()) {
                showToast("请输入复核人", false);
                return;
            }
            qcBean.setRECHECK_REASON(reason.getText().toString());
            qcBean.setRECHECK_PERSON(person.getText().toString());
            submit(ACTIONTYPE, qcBean, true);
            freeU_generalFragmentDialog.dismiss();
        });

        freeU_generalFragmentDialog.setLayout(view);
        freeU_generalFragmentDialog.show(getSupportFragmentManager(), "SUBMIT_DIALOG");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        //选择照片
//        if ((requestCode == 1 || requestCode == 2 || requestCode == 3) && resultCode == RESULT_OK) {
//            List<Uri> result = Matisse.obtainResult(data);
//            List<QCCheckBean.QCFORMDTO.ANNEXURLDTO> ANNEX_URL_LIST = new ArrayList<>();
//            for (Uri uri : result) {
//                try {
//                    Bitmap bitmap = getBitmapFromUri(uri);
//                    String base64Str = bitmapToBase64(bitmap);
//
//                    QCCheckBean.QCFORMDTO.ANNEXURLDTO item = new QCCheckBean.QCFORMDTO.ANNEXURLDTO();
//                    item.setANNEX_URL(base64Str);
//                    ANNEX_URL_LIST.add(item);
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            if (requestCode == 1) {
//                QCCheckBean.QCFORMDTO.ITEMLINESDTO itemlinesdto = mCheckAdapter.getData().get(currentUploadPosition);
//                itemlinesdto.setANNEX_URL_LIST(ANNEX_URL_LIST);
//                rvCheckList.post(() -> {
//                    mCheckAdapter.notifyItemChanged(currentUploadPosition);
//                });
//            }else if(requestCode == 2){
//                QCCheckBean.QCFORMDTO.DATALINESDTO datalinesdto = mMeasurementAdapter.getData().get(currentUploadPosition);
//                datalinesdto.setANNEX_URL_LIST(ANNEX_URL_LIST);
//                rvMeasurementList.post(() -> {
//                    mMeasurementAdapter.notifyItemChanged(currentUploadPosition);
//                });
//            }else {
//                QCCheckBean.QCFORMDTO.SPCLINESDTO spclinesdto = mSPCAdapter.getData().get(currentUploadPosition);
//                spclinesdto.setANNEX_URL_LIST(ANNEX_URL_LIST);
//                rvSPCList.post(() -> {
//                    mSPCAdapter.notifyItemChanged(currentUploadPosition);
//                });
//            }
//        }

//        拍照
        if ((requestCode == 1 || requestCode == 2 || requestCode == 3) && resultCode == RESULT_OK) {
            Uri uri1 = Uri.fromFile(new File(mFilePath));
            ContentResolver cr = this.getContentResolver();
            try {
                InputStream is = cr.openInputStream(uri1);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 3;
                Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
                String imageData = bitmapToBase64(bitmap);
                QCCheckBean.QCFORMDTO.ANNEXURLDTO item = new QCCheckBean.QCFORMDTO.ANNEXURLDTO();
                item.setANNEX_URL(imageData);

                if (!imageData.equals("")) {
                    if (requestCode == 1) {
                        mCheckAdapter.getData().get(currentUploadPosition).getANNEX_URL_LIST().add(item);
                        rvCheckList.post(() -> {
                            mCheckAdapter.notifyItemChanged(currentUploadPosition);
                        });
                    } else if (requestCode == 2) {
                        mMeasurementAdapter.getData().get(currentUploadPosition).getANNEX_URL_LIST().add(item);
                        rvMeasurementList.post(() -> {
                            mMeasurementAdapter.notifyItemChanged(currentUploadPosition);
                        });
                    } else {
                        mSPCAdapter.getData().get(currentUploadPosition).getANNEX_URL_LIST().add(item);
                        rvSPCList.post(()->{
                            mSPCAdapter.notifyItemChanged(currentUploadPosition);
                        });
                    }
                } else {
                    showToast("图片加载失败", false);
                }
            } catch (Exception e) {
                Log.i("upImage", e.toString());
            }
        }

    }


    // 通过Uri加载Bitmap的辅助方法
    private Bitmap getBitmapFromUri(Uri uri) throws IOException {
        return getContentResolver().openInputStream(uri) != null
                ? BitmapFactory.decodeStream(getContentResolver().openInputStream(uri))
                : null;
    }


    private static String bitmapToBase64(Bitmap bitmap) {
        if (bitmap == null) return null;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] bitmapBytes = baos.toByteArray();
            return Base64.encodeToString(bitmapBytes, Base64.NO_WRAP); // NO_WRAP更适合传输
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


//    private static String bitmapToBase64(Bitmap bitmap) {
//        String result = null;
//        ByteArrayOutputStream baos = null;
//        try {
//            if (bitmap != null) {
//                baos = new ByteArrayOutputStream();
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//
//                baos.flush();
//                baos.close();
//
//                byte[] bitmapBytes = baos.toByteArray();
//                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (baos != null) {
//                    baos.flush();
//                    baos.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return result;
//    }

}